<template>
	<label :class="['v-radio', { 'v-radio--disabled': isDisabled, 'v-radio--checked': isChecked }]" @click="handleChange">
		<span class="v-radio-input">
			<span v-if="isChecked" class="v-radio-inner"></span>
		</span>
		<span class="v-radio-label">
			<slot>{{ item.label }}</slot>
		</span>
	</label>
</template>

<script setup lang="ts">
import { inject, computed } from 'vue';

interface RadioItem {
	label: string;
	value: string | number;
}

const props = defineProps({
	value: {
		type: [String, Number],
		default: ''
	},
	item: {
		type: Object as () => RadioItem,
		required: true
	},
	disabled: {
		type: Boolean,
		default: false
	}
});

const radioGroup = inject('radioGroup', null);
const isDisabled = computed(() => {
	return radioGroup ? radioGroup.disabled.value || props.disabled : props.disabled;
});

const isChecked = computed(() => {
	return radioGroup ? radioGroup.value.value === props.item.value : props.value === props.item.value;
});

// 获取 radioGroup 的默认值
const radioGroupDefaultValue = computed(() => {
	return radioGroup ? (radioGroup as any).defaultValue : '';
});

const handleChange = () => {
	if (isDisabled.value) return;

	if (radioGroup) {
		// 如果当前选中，则取消选择，设置为默认值
		if (isChecked.value) {
			radioGroup.emitUpdate(radioGroupDefaultValue.value);
		} else {
			radioGroup.emitUpdate(props.item.value);
		}
	} else {
		// 如果是单独使用，直接更新值
		const newValue = isChecked.value ? '' : props.item.value;
		emit('update:value', newValue);
		emit('change', newValue);
	}
};

const emit = defineEmits(['update:value', 'change']);
</script>

<style lang="scss" scoped>
.v-radio {
	display: flex;
	align-items: center;
	cursor: pointer;
	font-size: 14px;
	color: #606266;
	transition: all 0.3s;
	margin-right: 16px;

	&:last-child {
		margin-right: 0;
	}

	&--disabled {
		color: #c0c4cc;
		cursor: not-allowed;

		.v-radio-input {
			background-color: #f5f7fa;
			border-color: #e4e7ed;
			cursor: not-allowed;
		}
	}

	&--checked {
		.v-radio-input {
			border-color: #287afa !important;

			.v-radio-inner {
				background-color: #287afa !important;
			}
		}
	}

	.v-radio-input {
		display: inline-block;
		width: 28rpx;
		height: 28rpx;
		border: 2px solid #dcdfe6;
		border-radius: 50%;
		background-color: transparent;
		position: relative;
		margin-right: 8px;
		cursor: pointer;
		transition: all 0.3s;
		vertical-align: middle;
		text-align: center;

		.v-radio-inner {
			display: inline-block;
			width: 16rpx;
			height: 16rpx;
			border-radius: 50%;
			background-color: #fff;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%) scale(1);
			transition: all 0.3s;
		}
	}

	.v-radio-label {
		display: inline-block;
		font-size: 22rpx;
	}
}
</style>
